
from PyQt4 import QtGui,QtCore
from ftllibs.FTL import CHAMPS as CHAMPS
from ftllibs.FTL import ITEMS as ITEMS
from ftllibs.FTL import RecommendedDS as RecommendedDS
from ftllibs.ui.UI_ChampDisplay import UI_ChampDisplay
from ftllibs.ui.UI_ItemMenu import ItemMenu
import copy

class RecommendedTab(QtGui.QWidget):
    def __init__(self,ChampID):
        super(RecommendedTab,self).__init__()
        self.MasterLayout = QtGui.QGridLayout()
        self.setLayout(self.MasterLayout)
        self.ChampID=ChampID
        self.Champ = CHAMPS.GetChampCopy(ChampID)
        self.unsaved=False
        self.NewBuild=True
        self.initUI()
        self.recomm={}

    def initUI(self):
        self.view = QtGui.QListView()
        self.model=RecommendedDS.GetRecommendedDataModel()
        self.view.setModel(self.model)
        self.view.setFixedWidth(300)
        self.view.setContextMenuPolicy(3) # Qt.CustomContextMenu
        self.BuildNameLabel = QtGui.QLabel('<h1>New Unsaved Build</h1>')
        self.AddButton=QtGui.QPushButton('Add')
        self.SaveButton=QtGui.QPushButton('Save')
        self.ButtonLayout=QtGui.QGridLayout()
        self.ButtonLayout.addWidget(self.AddButton,0,0,1,2)
        self.ButtonLayout.addWidget(self.SaveButton,1,0,1,2)
        self.ItemMenu=ItemMenu(self)
        
        self.IconAndNameLayout=QtGui.QHBoxLayout()
        self.ChampDisplay=UI_ChampDisplay(parent=self,ChampID=self.ChampID)
        print "RecommendedTab: self.ChampDisplay: ",self.ChampDisplay
        self.IconAndNameLayout.addWidget(self.ChampDisplay)
        self.MasterLayout.addWidget(self.AddButton,0,1,1,1)
        self.MasterLayout.addWidget(self.SaveButton,1,1,1,1)
        self.MasterLayout.addWidget(self.view,2,1,3,1)
        self.MasterLayout.addLayout(self.IconAndNameLayout,0,2,1,1,QtCore.Qt.AlignHCenter)
        self.Section1=RecommendedItemDisplay(self)
        self.Section2=RecommendedItemDisplay(self)
        self.Section3=RecommendedItemDisplay(self)
        self.Section4=RecommendedItemDisplay(self)
        self.MasterLayout.addWidget(self.Section1,1,2,1,1)
        self.MasterLayout.addWidget(self.Section2,2,2,1,1)
        self.MasterLayout.addWidget(self.Section3,3,2,1,1)
        self.MasterLayout.addWidget(self.Section4,4,2,1,1)
        self.MasterLayout.addWidget(self.ItemMenu,0,3,5,1)
        self.AddButton.clicked.connect(self.AddRecommended)
        self.SaveButton.clicked.connect(self.SaveRecommended)
        self.view.clicked.connect(self.LoadRecommended)
        
    def CustomContext(self,pos):
        index=self.view.indexAt(pos)
        if index.isValid():
            self.ContextMenu.exec_(self.view.mapToGlobal(pos))
        else:
            self.AddContextMenu.exec_(self.view.mapToGlobal(pos))
            

    def AddRecommended(self):
        text,ok = QtGui.QInputDialog.getText(self,'Add New Build','Name your build:',text='Unnamed Build')
        if ok:
            lastrow=self.model.rowCount()
            print "AddRecommended: lastrow: ", lastrow
            self.model.insertRows(lastrow,1,text)
            index = self.model.createIndex(lastrow,0)
            self.view.setCurrentIndex(index)
            if self.NewBuild:
                self.NewBuild=False
                self.recomm=self.model.loadRecommended(self.model.CurrentRCID)
                self.SaveRecommended()
                self.LoadRecommended()
            else:
                self.LoadRecommended()
    
    def SaveRecommended(self):
        if self.NewBuild:
            self.AddRecommended()
        else:
            for i in range(1,7):
                self.recomm["champion"]=self.Champ.InternalName
                self.recomm["section1item%s" % str(i)]=self.Section1.ItemList[str(i)]
                self.recomm["section2item%s" % str(i)]=self.Section2.ItemList[str(i)]
                self.recomm["section3item%s" % str(i)]=self.Section3.ItemList[str(i)]
                self.recomm["section4item%s" % str(i)]=self.Section4.ItemList[str(i)]
            self.model.saveRecommended(self.recomm)
            self.unsaved=False


    def LoadRecommended(self):
        self.CheckSave()
        index=self.view.currentIndex()
        RCID=self.model.getRCID(index.row())
        self.recomm=self.model.loadRecommended(RCID)
        sec1 = []
        sec2 = []
        sec3 = []
        sec4 = []
        for i in range(1,7):
            sec1.append(self.recomm["section1item%s" % str(i)])
            sec2.append(self.recomm["section2item%s" % str(i)])
            sec3.append(self.recomm["section3item%s" % str(i)])
            sec4.append(self.recomm["section4item%s" % str(i)])
        print self.recomm
        print sec1
        self.Section1.setItems(sec1)
        self.Section2.setItems(sec2)
        self.Section3.setItems(sec3)
        self.Section4.setItems(sec4)
        self.NewBuild=False
        self.unsaved=False

    def RequestClose(self):
        print "BuildTab -> RequestClose called"
        self.close()

    def CheckSave(self):
        if self.unsaved:
            ok = QtGui.QMessageBox.question(self,'Save Changes ?',"Do you want to save your changes ?","Yes","No")
            if ok == 0:
                self.SaveBuild()
    

class RecommendedItemDisplay(QtGui.QWidget):
    ItemChange = QtCore.pyqtSignal()
    def __init__(self,parent=None):
        super(RecommendedItemDisplay,self).__init__()
#        self.setAutoFillBackground(False)
#        self.setStyleSheet("QWidget { background-color: red }")
        self.parent = parent
        self.setFixedSize(500,74)
        self.setAcceptDrops(True)
        self.MasterLayout = QtGui.QGridLayout()
        self.ItemLayout = QtGui.QHBoxLayout()
        self.ItemLayout.setSpacing(1)
        self.ItemLayout.setAlignment(QtCore.Qt.AlignLeft)
        self.setLayout(self.MasterLayout)
        self.NoItemPix=QtGui.QPixmap("images/icons/cross_normal_hover.png")
        self.Title=""
        self.ItemList = {"1":"None","2":"None","3":"None","4":"None","5":"None","6":"None","7":"None","8":"None"}

    def paintEvent(self,e):
        painter = QtGui.QPainter(self)
        pen = QtGui.QPen()
        brush = QtGui.QBrush()
        brush.setColor(QtGui.QColor(0,0,0))
        brush.setStyle(1)
        pen.setWidth(3)
        pen.setBrush(brush)
        pen.setColor(QtGui.QColor(0,200,0))
        painter.setPen(pen)
        painter.drawRoundedRect(4,0,72,72,6,6)
        painter.drawRoundedRect(88,0,72,72,6,6)
        painter.drawRoundedRect(172,0,72,72,6,6)
        painter.drawRoundedRect(256,0,72,72,6,6)
        painter.drawRoundedRect(340,0,72,72,6,6)
        painter.drawRoundedRect(424,0,72,72,6,6)
        for i in range(1,7):
            if self.ItemList[str(i)] == "None":
                painter.drawPixmap(26+84*(i-1),20,self.NoItemPix)
            else:
                painter.drawPixmap(9+84*(i-1),4,ITEMS.ITEMS[self.ItemList[str(i)]].IconData.Default)

    def dragEnterEvent(self,e):
        e.accept()

    def mouseReleaseEvent(self,e):
        position = e.pos()
        pos = False
        print "BuildItemDisplay: mouseReleaseEvent: \"%s\"" % (position)
        if position.x() > 4 and position.x() < 72:
            pos = 1
        elif position.x() >= 88 and position.x() < 88+77:
            pos = 2
        elif position.x() >= 172 and position.x() < 172+77:
            pos = 3
        elif position.x() >= 256 and position.x() < 256+77:
            pos = 4
        elif position.x() >= 340 and position.x() < 340+77:
            pos = 5
        elif position.x() >= 424 and position.x() < 424+77:
            pos = 6
        if pos:
            self.delItem(pos)
            self.update()

    def dropEvent(self,e):
        item = e.mimeData().text()
        position = e.pos()
        pos = 1
        print "BuildItemDisplay: drop action: \"%s\";\"%s\"" % (item,position)
        if position.x() > 4 and position.x() < 72:
            pos = 1
        elif position.x() >= 88 and position.x() < 88+77:
            pos = 2
        elif position.x() >= 172 and position.x() < 172+77:
            pos = 3
        elif position.x() >= 256 and position.x() < 256+77:
            pos = 4
        elif position.x() >= 340 and position.x() < 340+77:
            pos = 5
        elif position.x() >= 424 and position.x() < 424+77:
            pos = 6
        self.addItem(pos,item)
        self.update()

    def setItems(self,items):
        self.clearItems()
        print "RecommendedItemDisplay: setItems: 'items':" ,items
        for i in range(0,len(items)):
            itemid=items[i]
            if not itemid == "None":
                self.addItem(i,itemid)
        #self.Title="<h1>%s</h1>" % (items['title'])
        self.update()

    def clearItems(self):
        self.ItemList = {"1":"None","2":"None","3":"None","4":"None","5":"None","6":"None","7":"None","8":"None"}
        self.update()
#        self.parent.unsaved=True

    def addItem(self,pos,itemid):
        self.ItemList[str(pos)]=str(itemid)
        self.update()
        self.ItemChange.emit()
        self.parent.unsaved=True

    def delItem(self,pos):
        self.ItemList[str(pos)]="None"
        self.update()
        self.ItemChange.emit()
        self.parent.unsaved=True